package com.ict.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ict.api.dto.IctOrderDTO;
import com.ict.api.dto.IctOrderPayDTO;
import com.ict.api.entity.IctOrder;
import com.ict.api.entity.IctOrderItem;
import com.ict.api.entity.IctSkuStock;
import com.ict.api.result.ApiResponse;
import com.ict.api.vo.IctOrderVO;
import com.ict.api.vo.PageResult;
import com.ict.mapper.IctOrderItemMapper;
import com.ict.mapper.IctOrderMapper;
import com.ict.mapper.IctSkuStockMapper;
import com.ict.service.IctOrderService;
import com.ict.util.GeneratorCode;
import com.ict.util.UserHolderUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author wjp
 * @since 2025-03-23
 */
@Service
public class IctOrderServiceImpl extends ServiceImpl<IctOrderMapper, IctOrder> implements IctOrderService {

    @Resource
    private IctOrderMapper orderMapper;

    @Resource
    private IctOrderItemMapper orderItemMapper;

    @Resource
    private IctSkuStockMapper skuStockMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse<IctOrderVO> createOrder(IctOrderDTO orderCreateDTO) {
        // 计算订单总金额
        BigDecimal totalAmount = orderCreateDTO.getCartItems().stream()
                .map(item -> item.getPrice().multiply(BigDecimal.valueOf(item.getQuantity()))) // price * quantity
                .reduce(BigDecimal.ZERO, BigDecimal::add); // sum 所有金额

        // 生成订单对象
        IctOrder order = new IctOrder();
        order.setUserId(UserHolderUtils.getUserId());
        order.setOrderSn(GeneratorCode.generateOrderSn());
        order.setTotalAmount(totalAmount);
        order.setPayAmount(totalAmount);
        order.setStatus(0); // 0: 待支付
        order.setPayType(0);
        order.setNote(orderCreateDTO.getNote());

        // 插入订单
        orderMapper.insert(order);

        // 插入订单明细
        List<IctOrderItem> orderItems = orderCreateDTO.getCartItems().stream().map(item -> {
            IctOrderItem orderItem = new IctOrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(item.getProductId());
            orderItem.setProductQuantity(item.getQuantity());
            orderItem.setProductPrice(item.getPrice());
            return orderItem;
        }).collect(Collectors.toList());

        orderItemMapper.insertBatchSomeColumn(orderItems);

        IctOrderVO ictOrderVO = new IctOrderVO();
        ictOrderVO.setOrderId(order.getId());
        ictOrderVO.setOrderSn(order.getOrderSn());
        return ApiResponse.success(ictOrderVO);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse<String> payOrder(Long orderId, IctOrderPayDTO orderPayDTO) {
        // 查询订单是否存在且未支付
        IctOrder order = orderMapper.selectById(orderId);
        if (order == null) {
            return ApiResponse.error("订单不存在");
        }
        if (order.getStatus() != 0) { // 0: 未支付
            return ApiResponse.error("订单已支付或已取消");
        }

        // TODO:: 调用第三方支付接口/跳转支付二维码页面

        // 更新订单状态为已支付
        LambdaUpdateWrapper<IctOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(IctOrder::getStatus, 1) // 1: 已支付
                .set(IctOrder::getPaymentTime, LocalDateTime.now()) // 记录支付时间
                .set(IctOrder::getPayType, orderPayDTO.getPayType())
                .eq(IctOrder::getId, orderId)
                .eq(IctOrder::getStatus, 0); // 仅更新未支付订单

        int updated = orderMapper.update(null, updateWrapper);

        if (updated > 0) {
            return ApiResponse.success("支付成功");
        } else {
            return ApiResponse.error("支付失败，请稍后重试");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResponse<String> cancelOrder(Long orderId) {
        // 查询订单是否存在且未支付
        IctOrder order = orderMapper.selectById(orderId);
        if (order == null) {
            return ApiResponse.error("订单不存在");
        }
        if (order.getStatus() != 0) { // 0: 待支付
            return ApiResponse.error("订单已支付或已取消");
        }

        // 更新订单状态为已取消
        LambdaUpdateWrapper<IctOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(IctOrder::getStatus, 4) // 4: 已取消
                .eq(IctOrder::getId, orderId)
                .eq(IctOrder::getStatus, 0); // 仅更新未支付订单

        int updated = orderMapper.update(null, updateWrapper);
        if (updated <= 0) {
            return ApiResponse.error("订单取消失败，请稍后重试");
        }

        // 查询订单包含的商品
        List<IctOrderItem> orderItems = orderItemMapper.selectList(
                new LambdaUpdateWrapper<IctOrderItem>().eq(IctOrderItem::getOrderId, orderId)
        );

        // 释放库存
        for (IctOrderItem item : orderItems) {
            LambdaUpdateWrapper<IctSkuStock> stockUpdateWrapper = new LambdaUpdateWrapper<>();
            stockUpdateWrapper
                    .setSql("stock = stock + " + item.getProductQuantity() + ", lock_stock = lock_stock - " + item.getProductQuantity())
                    .eq(IctSkuStock::getProductId, item.getProductId())
                    .ge(IctSkuStock::getLockStock, item.getProductQuantity()); // 确保锁定库存足够

            skuStockMapper.update(null, stockUpdateWrapper);
        }

        return ApiResponse.success("订单已取消");
    }

    @Override
    public ApiResponse<PageResult<IctOrderVO>> getOrderList(IctOrderDTO orderQueryDTO) {
        // 创建分页对象
        IPage<IctOrder> page = new Page<>(orderQueryDTO.getPage(), orderQueryDTO.getPageSize());

        // 构造查询条件
        LambdaQueryWrapper<IctOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(IctOrder::getUserId, orderQueryDTO.getUserId());

        if (orderQueryDTO.getStatus() != null) {
            queryWrapper.eq(IctOrder::getStatus, orderQueryDTO.getStatus());
        }

        // 查询订单数据
        IPage<IctOrder> orderPage = orderMapper.selectPage(page, queryWrapper);

        // 转换为 VO 视图对象
        IPage<IctOrderVO> orderVOPage = orderPage.convert(order -> {
            IctOrderVO orderVO = new IctOrderVO();
            orderVO.setOrderId(order.getId());
            orderVO.setOrderSn(order.getOrderSn());
            orderVO.setTotalAmount(order.getTotalAmount());
            orderVO.setStatus(order.getStatus());
            return orderVO;
        });

        PageResult<IctOrderVO> pageResult = new PageResult<>(orderQueryDTO.getPage(), orderQueryDTO.getPageSize(), orderVOPage.getTotal(), orderVOPage.getRecords());
        return ApiResponse.success(pageResult);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public IctOrder createOrder(Long userId, Integer paymentType, List<IctOrderItem> orderItems) {
        BigDecimal totalAmount = orderItems.stream()
                .map(item -> item.getProductPrice().multiply(BigDecimal.valueOf(item.getProductQuantity())))
                .reduce(BigDecimal.ZERO, BigDecimal::add);

        IctOrder order = new IctOrder();
        order.setUserId(userId);
        order.setOrderSn(GeneratorCode.generateOrderSn());
        order.setTotalAmount(totalAmount);
        order.setPayAmount(totalAmount);
        order.setStatus(0);
        order.setPayType(paymentType);

        orderMapper.insert(order);

        for (IctOrderItem orderItem : orderItems) {
            orderItem.setOrderId(order.getId());
            orderItemMapper.insert(orderItem);
        }

        return order;
    }
}
